package studentproject.dao;

import studentproject.domain.Student;

import java.io.*;
import java.util.ArrayList;

public class OtherStudentDao extends BaseStudentDao {
    private static ArrayList<Student> arr = new ArrayList<>();

    static {
        System.out.println("-------DAO加载了-------");
        readStudent(arr);
    }

    private static void readStudent(ArrayList<Student> arr){
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src\\studentproject\\dao\\student.txt"));
            byte [] bytes = new  byte[1024*1024];
            int len = bis.read(bytes);
            String read = new String(bytes,0,len);

            String [] readArr = read.split(System.lineSeparator());
            for (String s : readArr) {
                String [] stu = s.split("，");
                Student student = new Student(stu[0],stu[1],stu[2],stu[3]);
                arr.add(student);
            }
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean addStudent(Student student){
        arr.add(student);
        try {
            saveStudentMessage(arr);
        } catch (IOException e) {
            System.out.println("add方法出错啦");
        }
        return true;
    }

    @Override
    public Student[] findAll() {
        Student[] students = new Student[arr.size()];

        for (int i = 0; i < arr.size(); i++) {
            students[i] = arr.get(i);
        }

        return students;
    }
    @Override
    public int isExist(String id) {
        //调用dao，拿到所有容器数据
        int index = -1;
        for (int i = 0; i < arr.size(); i++) {
            Student stu = arr.get(i);
            if(id.equals(stu.getId())){
                index = i;
                break;

            }
        }
        return index;
    }


    public static void saveStudentMessage(ArrayList<Student> list) throws IOException {
        FileOutputStream fos = new FileOutputStream("src\\studentproject\\dao\\student.txt");
        try {
            for (Student stu : list) {
                fos.write(stu.toString().getBytes());
                fos.write("\r\n".getBytes());
            }
        } catch (IOException e) {
            System.out.println("save方法出错啦");
        } finally {
            fos.close();
        }

    }

    @Override
    public boolean updateStudent(Student stu) {
        int index = isExist(stu.getId());
        arr.set(index,stu);
        try {
            saveStudentMessage(arr);
        } catch (IOException e) {
            System.out.println("update方法出错啦");
        }
        return true;
    }

    @Override
    public boolean deleteStudent(int index) {
        arr.remove(index);
        try {
            saveStudentMessage(arr);
        } catch (IOException e) {
            System.out.println("delete方法出错啦");
        }
        return true;
    }
}
